<?php

namespace app\dao\user;

use app\dao\BaseDao;
use app\model\user\User;

/**
 * Class User
 * @package app\dao\user
 */
class UserDao extends BaseDao
{
    /**
     * Description: 设置模型
     * @return string
     */
    protected function setModel(): string
    {
        return User::class;
    }

    /**
     * Description: 获取数据列表
     *
     * @param array $where
     * @param int   $page
     * @param int   $limit
     * @param array $with
     * @param array $attr
     *
     * @throws \ReflectionException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @return array
     */
    public function queryList(array $where, int $page, int $limit, array $with = [], array $attr = [])
    {
        return $this->search($where)->page($page, $limit)->with($with)->withAttr($attr)->order('uid desc')->select()->toArray();
    }
    
    //=================接口===================
    public function queryApiList(array $where, int $page, int $limit, string $field, array $with = [], array $attr = [])
    {
        return $this->search($where)
            ->when($page && $limit, function ($query) use ($page, $limit) {
                $query->page($page, $limit);
            })->field($field)->with($with)->withAttr($attr)->order('id asc')->select();

    }

    /**
     * Description:获取当前下级总人数
     *
     * @param array $ids
     *
     * @throws \ReflectionException
     * @return mixed
     */
    public function queryDistributTotalUser(array $ids)
    {
        return $this->search()
            ->whereIn('pid', $ids)
            ->field('count(pid) as total_user_number,pid')
            ->group('pid')
            ->order('pid desc')
            ->select();
    }

    /**
     * Description: 某个字段累加某个数值
     *
     * @param int    $uid
     * @param string $field
     * @param int    $num
     *
     * @return mixed
     */
    public function incField(int $uid, string $field, int $num = 1)
    {
        return $this->getModel()->where('id', $uid)->inc($field, $num)->update();
    }

    /**
     * Description: 某个字段递减某个数值
     *
     * @param int    $uid
     * @param string $field
     * @param int    $num
     *
     * @return mixed
     */
    public function decField(int $uid, string $field, int $num = 1)
    {
        return $this->getModel()->where('id', $uid)->inc($field, $num)->update();
    }
}

